﻿using System;
using _5E.Infrastructure.Domain;
using _5E.Infrastructure.UnitOfWork;
using NHibernate;

namespace _5E.NHibernateRepository.UnitOfWork
{
    public class NHibernateUnitOfWork : IUnitOfWork
    {
        public void RegisterAmended(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository)
        {
            SessionFactory.CurrentSession.SaveOrUpdate(entity);
        }

        public void RegisterNew(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository)
        {
            SessionFactory.CurrentSession.Merge(entity);
        }

        public void RegisterRemoved(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository)
        {
            SessionFactory.CurrentSession.Delete(entity);
        }

        public void Comit()
        {
            using (ITransaction trans = SessionFactory.CurrentSession.BeginTransaction())
            {
                try
                {
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }
    }
}
